<!-- 素材选择 -->
<template>
  <BasicModal 
    v-bind="$attrs" 
    @register="registerModal" 
    :title="title" 
    width="1200px"  
    @ok="handleSubmit" 
    destroyOnClose 
  >
    <div class="select-link-left">
      <MyTreeSelect 
        v-bind="treeProps"
        @select="onTreeSelect" 
        ref="materialGroupTreeRef"
      />
    </div>
    <div class="select-link-right h-full">
      <component 
        v-if="selectComp && selectComp.component" 
        :is="selectComp.component" 
        :key="selectComp.id"
        v-model:value="selectId"
        :allData="allData" 
        :linkData="linkData"
        :treeSelectId="treeSelectId"
        @extParams="handleExtParams"
        ref="linkDataRef"
      />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, toRaw, shallowRef, defineAsyncComponent, watchEffect, provide, onUnmounted } from 'vue';
import { useDesign } from '/@/hooks/web/useDesign'
import { BasicModal, useModalInner } from '/@/components/Modal';
import { MyTreeSelect, MyTreeProps } from '/@/components/BizTreeSelect';
import { useModal } from '/@/components/Modal';
import { listDiyAppLink } from '/@/api/common/api'
import {  } from './data'
import { filter as filterTree, eachTree } from '/@/utils/helper/treeHelper'
import { propTypes } from '/@/utils/propTypes';
import { useAttrs } from '/@/hooks/core/useAttrs';
import EXCEPTION_COMPONENT from '/@/views/sys/exception/Exception.vue'

let dynamicViewsModules: Record<string, () => Promise<Recordable>>;
let dynamicComponentsModules: Record<string, () => Promise<Recordable>>;

const treeSelectId = ref<string>()
const extParams = ref<any>({})
const selectId = ref<string>()
const selectLinkParam = ref<any>()
const linkDataRef = ref()
const attrs = useAttrs({ excludeDefaultKeys: false });

const emit = defineEmits(['register', 'success', 'change']);

const props = defineProps({
  materialType: propTypes.string,
  selectCount: propTypes.number.def(1)
});

const selectComp = shallowRef<any>({})
const linkData = ref<Map<string, any>>(new Map())
const allData = new Map()

const handleListDiyAppLink = async (params) => {
  const data : any = await listDiyAppLink(params)
  allData.clear()
  linkData.value.clear()
  eachTree(data, (item, _parent) => {
    allData.set(item.id, item)
  })

  let ungroupedLinke : any = new Map()
  for (const item of data) {
    console.log('item.children', item.children)
    if (item.children) {
      for (const node of item.children) {
        if (node.type === 'link_page') {
          const list = ungroupedLinke.get(item.code) || []
          list.push(node)
          ungroupedLinke.set(item.code, list)
        }
      }
    }
  }


  let newData : any = []
  newData = filterTree(data, (node) => {
    if (node.type === 'link_group') {
      const parentNode = allData.get(node.parentId)
      const linkList = linkData.value.get(parentNode.code) || []
      linkList.push(allData.get(node.id))
      linkData.value.set(parentNode.code, linkList)
    }
    return node.type === 'menu'
  })
  ungroupedLinke.forEach((value, key, map) => {
    const ungroupedNode = {
      name: '未分组',
      children: value,
      code: 'default'
    }
    const tempData = linkData.value.get(key) || []
    tempData.push(ungroupedNode)
    console.log('tempData', tempData)
    linkData.value.set(key, tempData)
  })

  console.log('linkData', linkData.value)
  return newData
}

const treeProps = ref<MyTreeProps>({
  searchField: 'name',
  search: false,
  toolbar: false,
  api: handleListDiyAppLink,
  immediate: true,
  params: { 
    
  },
  enableDelete: true
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  setModalProps({ canFullscreen: false })
});

const title = computed(() => {
  // for (const key in MaterialType) {
  //   if (props.materialType === MaterialType[key].type) {
  //     return `选择${MaterialType[key].name}`
  //   }
  // }
  return `选择链接`
});

let timer = null
const materialGroupTreeRef = ref<any>()
const slectedRows = ref<any[]>([])
const { prefixCls } = useDesign('material')
provide('prefixCls', prefixCls)

watchEffect(() => {
  
})

function dynamicImport(component: string) {
  if (!component) {
    return undefined
  }
  component = `/${component}`
  if (!dynamicComponentsModules) {
    dynamicComponentsModules = import.meta.glob('/src/components/BizAppSelectLink/src/compontents/*.{vue,tsx}')
    for (const key in dynamicComponentsModules) {
      dynamicComponentsModules[key.substring(key.lastIndexOf('/'))] = dynamicComponentsModules[key]
      delete dynamicComponentsModules[key]
    }
  }

  if (!dynamicViewsModules) {
    dynamicViewsModules = import.meta.glob('/src/views/**/*.{vue,tsx}')
  }
  const dynamicModules = { ...dynamicComponentsModules, ...dynamicViewsModules }
  const keys = Object.keys(dynamicModules);
  const matchKeys = keys.filter((key) => {
    const k = key.replace('/src/views', '').replace('/src/components', '');
    const startFlag = component.startsWith('/');
    const endFlag = component.endsWith('.vue') || component.endsWith('.tsx');
    const startIndex = startFlag ? 0 : 1;
    const lastIndex = endFlag ? k.length : k.lastIndexOf('.');
    return k.substring(startIndex, lastIndex) === component;
  });

  if (matchKeys?.length === 1) {
    const matchKey = matchKeys[0];
    return defineAsyncComponent(dynamicModules[matchKey])
  } else if (matchKeys?.length > 1) {
    console.warn(
      'Please do not create `.vue` and `.TSX` files with the same file name in the same hierarchical directory under the views folder. This will cause dynamic introduction failure'
    );
    return;
  } else {
    // warn('在src/views/下找不到`' + component + '.vue` 或 `' + component + '.tsx`, 请自行创建!');
    return EXCEPTION_COMPONENT;
  }
}

function onTreeSelect(id) {
  const data = allData.get(id)
  if (data.children && data.children.length > 0 && data.children[0].type === 'menu') {
    return
  }
  treeSelectId.value = id
  selectComp.value = {
    component: dynamicImport(data.component),
    id
  }
  console.log('onTreeSelect', id, data.code, selectComp.value);
}

function handleExtParams(value) {
  extParams.value = value
}

async function handleSubmit(v) {
  const ret = { ...allData.get(selectId.value), extParams: toRaw(extParams.value) || {}}
  closeModal();
  console.log('selectData', ret)
  emit('change', ret)
}

</script>

<style lang="less">
.select-link-left {
  overflow: auto;
  border-right: 1px solid #f2f2f2;
  width: 230px;
  position: fixed;
  height: calc(100vh - 120px);
}

.select-link-right {
  overflow-y: auto;
  margin-left: 235px;
  width: auto;
  height: calc(100vh - 160px);
}

</style>